﻿using System;
using System.IO;
using System.Text;
using HorseRaceRe.Code.Helpers;
using HorseRaceRe.Code.Models;
using Newtonsoft.Json;
using XQColorful.SDK;
using XQColorful.SDK.EventArgs;
using XQColorful.SDK.Interface;

namespace HorseRaceRe.Code.Events
{
    public class EventCreateRace : IPluginEvent
    {
        public XQEventType EventType => XQEventType.Group;

        public void Process(XQEventArgs _e)
        {
            var e = new GroupMsgEventArgs(_e);

            if (e.Message == "创建赛马")
            {
                var msg = new StringBuilder();

                if (App.GroupGrounds.ContainsKey(e.FromGroup))
                {
                    //已经有比赛了
                    msg.AppendLine("本群已经开始了一场赛马比赛!");
                }
                else
                {
                    msg.AppendLine("发送 创建赛马 <赛马场配置> 来创建一个新的赛马比赛");
                    msg.AppendLine("当前的赛马场配置如下");

                    foreach (var file in Directory.GetFiles(PathHelper.GroundsDir, "*.json"))
                    {
                        msg.AppendLine(Path.GetFileNameWithoutExtension(file));
                    }
                }

                e.SendMsg(msg.ToString());
                return;
            }

            if (e.Message.StartsWith("创建赛马"))
            {
                var msg = new StringBuilder();

                if (App.GroupGrounds.ContainsKey(e.FromGroup))
                {
                    //已经有比赛了
                    msg.AppendLine("本群已经开始了一场赛马比赛!");
                }

                var name = e.Message.TrimStart("创建赛马".ToCharArray()).Trim();
                var json_path = Path.Combine(PathHelper.GroundsDir, name + ".json");
                if (File.Exists(json_path))
                {
                    try
                    {
                        RaceGround raceGround = new RaceGround(JsonConvert.DeserializeObject<RaceGroundInfo>(
                            File.ReadAllText(json_path)));
                        App.GroupGrounds.Add(e.FromGroup, raceGround);

                        if (App.Core.CheckUpdate(out var version))
                        {
                            msg.AppendLine("赛马Re有新版更新啦!");
                            msg.AppendLine("可以发送 赛马re 来查看更多信息!");
                        }
                        
                        msg.AppendLine("创建成功!");
                    }
                    catch (Exception exception)
                    {
                        msg.AppendLine(name + ".json 载入失败。(联系Bot的主人!)");
                        //throw;
                    }
                }
                else
                {
                    msg.AppendLine(name + ".json 不存在! (联系Bot的主人!)");

                }

                e.SendMsg(msg.ToString());
                return;
            }
        }
    }
}